<template>
  <div class="input-with-variable">
    <div class="input-area">
      <slot></slot>
      <VariableSelector 
        :event-id="eventId" 
        @select="selectVariable"
      />
    </div>
    
    <div class="variable-help-text">
      可以使用 ${变量名} 的形式引用变量，如 ${userName}
    </div>
    
    <!-- 显示当前选中变量 -->
    <div v-if="selectedVariables.length > 0" class="selected-variable-container">
      <el-tooltip 
        v-for="variable in selectedVariables"
        :key="variable.name"
        :content="getVariableDescription(variable)" 
        placement="top" 
        effect="light"
        :show-after="200"
      >
        <el-tag size="small" type="info" class="selected-variable-tag">
          <span class="scope-label">{{ variable.scope === 'global' ? '全局' : '局部' }}</span>
          <span class="variable-name">${{ variable.name }}</span>
        </el-tag>
      </el-tooltip>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import VariableSelector from './VariableSelector.vue'

const props = defineProps({
  eventId: {
    type: String,
    required: true
  },
  fieldName: {
    type: String,
    required: true
  },
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['insert-variable', 'update:modelValue'])
const store = useStore()

const selectedVariables = ref([])

// 获取变量描述
const getVariableDescription = (variable) => {
  if (!variable) return ''
  
  let description = `名称: ${variable.name}\n类型: ${getTypeText(variable.type)}`
  
  if (variable.description) {
    description += `\n描述: ${variable.description}`
  }
  
  return description
}

// 获取变量类型的中文名称
const getTypeText = (type) => {
  const typeMap = {
    'string': '字符串',
    'number': '数字',
    'boolean': '布尔值',
    'datetime': '日期时间',
    'array': '数组',
    'object': '对象'
  }
  return typeMap[type] || type
}

// 选择变量
const selectVariable = (variable) => {
  // 检查变量是否已存在
  const existingVarIndex = selectedVariables.value.findIndex(v => v.name === variable.name)
  if (existingVarIndex === -1) {
    selectedVariables.value.push(variable)
  }
  
  emit('insert-variable', variable, props.fieldName)
}

// 从文本中提取变量引用并添加到已选变量列表
const extractVariablesFromText = async (text) => {
  if (!text) {
    selectedVariables.value = []
    return
  }
  
  // 获取所有可用变量
  let allVariables = store.state.allAvailableVariables || []
  
  // 如果没有可用变量，先尝试加载
  if (allVariables.length === 0) {
    try {
      await store.dispatch('fetchAllAvailableVariables', props.eventId)
      allVariables = store.state.allAvailableVariables || []
    } catch (error) {
      console.error('获取变量失败:', error)
      return
    }
  }
  
  // 使用正则表达式匹配所有${变量名}格式的引用
  const variablePattern = /\${([^}]+)}/g
  let match
  const foundVariables = []
  
  while ((match = variablePattern.exec(text)) !== null) {
    const varName = match[1]
    // 在可用变量中查找匹配的变量
    const variable = allVariables.find(v => v.name === varName)
    if (variable && !foundVariables.some(v => v.name === varName)) {
      foundVariables.push(variable)
    }
  }
  
  selectedVariables.value = foundVariables
}

// 创建一个立即提取变量的函数
const tryExtractVariables = () => {
  const currentValue = props.modelValue
  if (currentValue) {
    // 如果变量已加载，立即提取
    if (store.state.allAvailableVariables && store.state.allAvailableVariables.length > 0) {
      extractVariablesFromText(currentValue)
    } else {
      // 否则先加载变量，然后再提取
      store.dispatch('fetchAllAvailableVariables', props.eventId).then(() => {
        extractVariablesFromText(currentValue)
      })
    }
  } else {
    // 如果没有值，清空选中变量
    selectedVariables.value = []
  }
}

// 监听父组件传入的model-value变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== undefined) {
    tryExtractVariables()
  }
}, { immediate: true })

// 监听事件ID变化
watch(() => props.eventId, (newId) => {
  if (newId) {
    tryExtractVariables()
  }
})

// 监听全局变量加载状态
watch(() => store.state.allAvailableVariables, (variables) => {
  if (variables && variables.length > 0 && props.modelValue) {
    extractVariablesFromText(props.modelValue)
  }
})

onMounted(() => {
  // 组件挂载后，尝试从初始文本中提取变量
  tryExtractVariables()
})
</script>

<style scoped>
.input-with-variable {
  display: flex;
  flex-direction: column;
}

.input-area {
  display: flex;
  align-items: center;
}

.variable-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.selected-variable-container {
  margin-top: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.selected-variable-tag {
  cursor: help;
  margin-right: 5px;
  margin-bottom: 5px;
}

.scope-label {
  opacity: 0.7;
  font-size: 11px;
  margin-right: 3px;
}

.variable-name {
  font-weight: 500;
}
</style> 